package com.wuuxiang.polestar.admin.filter;  
  
import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import com.alibaba.fastjson.JSON;
import com.wuuxiang.polestar.admin.dto.BaseReturnDTO;
import com.wuuxiang.polestar.admin.utils.JwtUtils;  
  
public class JwtFilter implements Filter{  
  
    @Override  
    public void init(FilterConfig filterConfig) throws ServletException {  
        // TODO Auto-generated method stub  
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,  
                filterConfig.getServletContext());  
          
    }  
  
    @Override  
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)  
            throws IOException, ServletException {  
          
        HttpServletRequest httpRequest = (HttpServletRequest)request;  
        String auth = httpRequest.getHeader("Authorization");  
        ((HttpServletResponse) response).setHeader("Access-Control-Allow-Origin", "*");
        
        if (httpRequest.getRequestURI().equals("/polestar/downloadAll")) {
        	chain.doFilter(request, response);  
            return; 
        }
        
        String subject = null;
		try {
			subject = JwtUtils.parserJWT(auth);
		} catch (Exception e) {
			
		}
        if(subject != null){
        	chain.doFilter(request, response);  
            return; 
        }
        HttpServletResponse httpResponse = (HttpServletResponse) response;  
        httpResponse.setCharacterEncoding("UTF-8");    
        httpResponse.setContentType("application/json; charset=utf-8");  
        httpResponse.setHeader("Access-Control-Allow-Headers", "Authorization,Content-type");
        //httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);  
        BaseReturnDTO returnDTO = new BaseReturnDTO();
        returnDTO.setErrorCode("499");
        returnDTO.setReturnCode(-1);
        returnDTO.setErrorText("未登录，或者登录过期，请重新登录！");
        httpResponse.getWriter().write(JSON.toJSONString(returnDTO));  
        return;  
    }  
    @Override  
    public void destroy() {  
        // TODO Auto-generated method stub  
          
    } 
     
}  